﻿using System;
using System.Text;
using Microsoft.SharePoint;
using Kiiro.Common.Entities;
using Kiiro.Common.Utility;
using Kiiro.ExceptionManagement;

using SetupFieldNames = Kiiro.Common.Utility.Constants.SetupFieldNames;
using SPListNames = Kiiro.Common.Utility.Constants.SPListNames;

namespace Kiiro.DataAccess
{
    public class SetupDA
    {
        #region Singleton
        private SetupDA ( )
        {
        }

        private static SetupDA instance = null;
        private static readonly object threadLock = new object ( );

        public static SetupDA Instance
        {
            get
            {
                lock ( threadLock )
                {
                    if ( instance == null )
                    {
                        instance = new SetupDA ( );
                    }
                }
                return instance;
            }
        }
        #endregion

        public Setup GetMidoriSetup ( Guid siteCollectionId, string serverRelativeUrl )
        {
            Setup setup = null;

            try
            {
                using ( SPWeb web = SPHelpers.GetPortalWeb ( siteCollectionId, serverRelativeUrl ) )
                {
                    SPList list = web.Lists [ SPListNames.Setup ];

                    if ( list != null )
                    {
                        StringBuilder queryText = new StringBuilder ( );

                        SPQuery query = new SPQuery ( );
                        query.RowLimit = 1;
                        query.Query = queryText.ToString ( );

                        SPListItemCollection listItems = list.GetItems ( query );

                        if ( listItems != null && listItems.Count > 0 )
                        {
                            setup = SPDataHelpers.MakeSetup ( listItems [ 0 ] );
                        }
                    }
                }
            }
            catch ( Exception ex )
            {
                ExceptionManager.HandleException ( ex, true );
            }

            return setup;
        }

        public Setup Save ( Setup setup, Guid siteCollectionId, string serverRelativeUrl )
        {
            SPList list = null;
            SPListItem listItem = null;
            try
            {
                if ( setup == null )
                    throw new Exception ( "Cannot SaveSetup() when Setup entity is null" );

                if ( setup.EditType != EditType.Unchanged )
                {
                    using (SPWeb web = SPHelpers.GetPortalWeb(siteCollectionId, serverRelativeUrl))
                    {
                        list = web.Lists[SPListNames.Setup];

                        if (list != null)
                        {
                            #region Get Item

                            listItem = setup.EditType == EditType.Created ? list.Folders.Add() : list.Folders.GetItemById(setup.Id);

                            switch (setup.EditType)
                            {
                                case EditType.Created:
                                    list.ParentWeb.AllowUnsafeUpdates = true;
                                    listItem.Update();
                                    list.ParentWeb.AllowUnsafeUpdates = false;

                                    listItem = list.Folders.GetItemById(listItem.ID);
                                    listItem[SetupFieldNames.ServerRelativeUrl] = listItem.Folder.ServerRelativeUrl;
                                    listItem[SetupFieldNames.SiteCollectionId] = list.ParentWeb.Site.ID;

                                    if (setup.CreatedBy != null && setup.CreatedBy.Id > 0)
                                        listItem[SetupFieldNames.CreatedBy] = setup.CreatedBy.Id;
                                    if (setup.CreatedDate != null && setup.CreatedDate != DateTime.MinValue)
                                        listItem[SetupFieldNames.CreatedDate] = setup.CreatedDate;

                                    break;

                                case EditType.Updated:
                                case EditType.Deleted:
                                default:
                                    break;
                            }

                            #endregion // Get Item

                            #region Set Item Properties

                            string pictureUrl = default(string);

                            if (listItem != null && setup.EditType != EditType.Deleted)
                            {
                                try
                                {
                                    SPFolder folder = listItem.Folder;
                                    if (folder.Exists && setup.LogoBytes != null && setup.LogoUrl != null)
                                    {
                                        pictureUrl = string.Format("{0}/{1}", folder.ServerRelativeUrl, setup.LogoUrl);
                                        folder.Files.Add(pictureUrl, setup.LogoBytes, true);
                                        listItem[SetupFieldNames.LogoUrl] = pictureUrl;
                                    }
                                    else if (string.IsNullOrEmpty(setup.LogoUrl))
                                    {
                                        listItem[SetupFieldNames.LogoUrl] = string.Empty;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    ExceptionManager.HandleException(ex, true);
                                }

                                listItem[SetupFieldNames.LicenseKey] = setup.LicenseKey;

                                if (setup.ModifiedBy != null && setup.ModifiedBy.Id > 0)
                                    listItem[SetupFieldNames.ModifiedBy] = setup.ModifiedBy.Id;
                                if (setup.ModifiedDate != null && setup.ModifiedDate != DateTime.MinValue)
                                    listItem[SetupFieldNames.ModifiedDate] = setup.ModifiedDate;

                                if (!string.IsNullOrEmpty(setup.Title))
                                    listItem[SetupFieldNames.Title] = setup.Title;

                                if (!string.IsNullOrEmpty(setup.Description))
                                    listItem [ SetupFieldNames.Description ] = setup.Description;

                                if ( !string.IsNullOrEmpty ( setup.SiteName ) )
                                    listItem [ SetupFieldNames.SiteName ] = setup.SiteName;

                                listItem [ SetupFieldNames.IsWPSandboxActivated ] = setup.IsWPSandboxActivated;
                                listItem [ SetupFieldNames.WPSandboxNavText ] = setup.WPSandboxNavText;

                                listItem[SetupFieldNames.SendEmailUpdates] = setup.SendEmailUpdates;
                                listItem[SetupFieldNames.AllowEmailReplies] = setup.AllowEmailReplies;

                                if (!string.IsNullOrEmpty(setup.EmailFromAddress))
                                    listItem[SetupFieldNames.EmailFromAddress] = setup.EmailFromAddress;
                                else
                                    listItem[SetupFieldNames.EmailFromAddress] = string.Empty;

                                if (!string.IsNullOrEmpty(setup.SMTPInfo))
                                    listItem[SetupFieldNames.SMTPInfo] = setup.SMTPInfo;
                                else
                                    listItem[SetupFieldNames.SMTPInfo] = string.Empty;

                                if (!string.IsNullOrEmpty(setup.POPInfo))
                                    listItem[SetupFieldNames.POPInfo] = setup.POPInfo;
                                else
                                    listItem[SetupFieldNames.POPInfo] = string.Empty;

                                if (!string.IsNullOrEmpty(setup.POPEmail))
                                    listItem[SetupFieldNames.POPEmail] = setup.POPEmail;
                                else
                                    listItem[SetupFieldNames.POPEmail] = string.Empty;

                                if (!string.IsNullOrEmpty(setup.POPPassword))
                                {
                                    if (listItem.Properties[SetupFieldNames.POPPassword] == null)
                                        listItem.Properties.Add(SetupFieldNames.POPPassword, setup.POPPassword);
                                    else
                                        listItem.Properties[SetupFieldNames.POPPassword] = setup.POPPassword;
                                }
                                else
                                    listItem.Properties[SetupFieldNames.POPPassword] = string.Empty;

                                listItem[SetupFieldNames.HoursPerDay] = setup.HoursPerDay;

                                listItem[SetupFieldNames.MSProjectIntegration] = setup.MSProjectIntegration;

                                if (setup.MinMSProjectPluginVer != null)
                                    listItem[SetupFieldNames.MinMSProjectPluginVer] = setup.MinMSProjectPluginVer;
                                else
                                    listItem[SetupFieldNames.MinMSProjectPluginVer] = "0.0.0.0";
                            }

                            #endregion // Set Item Properties

                            #region Update / Delete Item

                            SPWeb parentWeb = null;

                            try
                            {
                                parentWeb = list.ParentWeb;
                                parentWeb.AllowUnsafeUpdates = true;

                                if (setup.EditType != EditType.Deleted)
                                {
                                    listItem.Update();
                                    setup = SPDataHelpers.MakeSetup(listItem);
                                }
                                else
                                {
                                    // CANNOT delete Setup
                                }
                            }
                            catch (Exception ex)
                            {
                                ExceptionManager.HandleException(ex, true);
                            }
                            finally
                            {
                                if (parentWeb != null) parentWeb.AllowUnsafeUpdates = false;
                                if (parentWeb != null) parentWeb.Dispose();
                            }

                            #endregion // Update / Delete Item
                        }
                    }
                }
            }
            catch ( Exception ex )
            {
                ExceptionManager.HandleException ( ex, true );
            }

            return setup;
        }
    }
}

/*************************************************************************
 * 
 * $Log: /Internal Projects/Kiiro/Kiiro.DataAccess/SetupDA.cs $
 * 
 * 9     30/09/09 9:17a Shafia
 * 
 * 8     27/08/09 11:04a Shafia
 * Setup not required fields now set to empty when removed from the UI
 * 
 * 7     17/08/09 10:41a Camerons
 * Added check-in comments section
 * 
 ************************************************************************/